package com.opencursor;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.diagnostic.Logger;
import org.jetbrains.annotations.NotNull;

public class OpenInCursorAction extends AnAction {
    private static final Logger LOG = Logger.getInstance(OpenInCursorAction.class);

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) {
            LOG.warn("Project is null");
            return;
        }

        VirtualFile projectDir = project.getProjectFile().getParent();
        if (projectDir == null) {
            LOG.warn("Project directory is null");
            Messages.showErrorDialog(project, "无法获取项目目录", "错误");
            return;
        }

        // 获取项目的父目录
        VirtualFile parentDir = projectDir.getParent();
        if (parentDir == null) {
            LOG.warn("Parent directory is null");
            Messages.showErrorDialog(project, "无法获取项目父目录", "错误");
            return;
        }

        String cursorPath = CursorSettings.getInstance().getCursorPath();
        if (cursorPath.isEmpty()) {
            LOG.warn("Cursor path is not configured");
            Messages.showErrorDialog(project, "请先在设置中配置Cursor路径 (Tools -> Cursor Settings)", "错误");
            return;
        }

        try {
            LOG.info("Starting Cursor with path: " + cursorPath + " and directory: " + parentDir.getPath());
            ProcessBuilder processBuilder = new ProcessBuilder(cursorPath, parentDir.getPath());
            Process process = processBuilder.start();
            LOG.info("Cursor process started successfully");
        } catch (Exception ex) {
            LOG.error("Failed to start Cursor", ex);
            Messages.showErrorDialog(project, "启动Cursor失败: " + ex.getMessage(), "错误");
        }
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        e.getPresentation().setEnabled(e.getProject() != null);
    }
}